/**
 * 表单验证组合函数
 * 负责表单验证规则和验证逻辑
 */
import { reactive, computed } from 'vue';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';

export function useFormValidation() {
  // 表单验证规则 /^[a-z_]+$/
  const formRules = reactive({
    title: [
      {
        required: true,
        message: $p('menu.dev.action.field.title', '字段标题'),
        trigger: 'blur',
      },
    ],
    method: [
      {
        required: true,
        message: $p('menu.dev.action.field.method', '方法名'),
        trigger: 'blur',
      },
      {
        pattern: /^[a-z_][a-z0-9_]+$/,
        message: $t('common.message.validate.only_lower_under'),
      },
    ],
  });

  /**
   * 验证表单
   * @param {Object} refForm - 表单引用
   * @returns {Promise<boolean>} 验证结果
   */
  const validateForm = async (refForm) => {
    try {
      await refForm.validate();
      return true;
    } catch (error) {
      console.error('表单验证失败:', error);
      return false;
    }
  };

  /**
   * 清除表单验证
   * @param {Object} refForm - 表单引用
   */
  const clearValidate = (refForm) => {
    if (refForm) {
      refForm.clearValidate();
    }
  };

  /**
   * 重置表单字段
   * @param {Object} refForm - 表单引用
   */
  const resetFields = (refForm) => {
    if (refForm) {
      refForm.resetFields();
    }
  };

  return {
    formRules,
    validateForm,
    clearValidate,
    resetFields,
  };
}
